<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="queryName" placeholder="商品名称" style="width: 200px; margin: 5px 0 5px 0" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="queryType" placeholder="类型" clearable style="width: 150px; margin: 5px 0 5px 0" class="filter-item">
        <el-option v-for="item in typeOptions" :key="item" :label="item" :value="item" />
      </el-select>
      <el-select v-model="queryStats" placeholder="状态" clearable style="width: 150px; margin: 5px 0 5px 0" class="filter-item">
        <el-option v-for="item in StatsOptions" :key="item" :label="item" :value="item" />
      </el-select>
      <el-button class="filter-item" style="margin: 5px 0 5px 0" type="primary" icon="el-icon-search" @click="handleFilter" />
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate" />
      <br>
    </div>

    <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column label="名称" width="120" align="center">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="icon" width="120" align="center">
        <template slot-scope="scope">
          <img :src="scope.row.icon" min-width="70" height="70" />
        </template>
      </el-table-column>
      <el-table-column label="类型" width="110" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.type | typeCssFilter">
            {{ row.type | typeFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="180" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.stats | statusCssFilter">
            {{ row.stats | statusFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="兑换所需金豆/余额" width="180" align="center">
        <template slot-scope="scope">
          {{ scope.row.price }}
        </template>
      </el-table-column>
      <el-table-column label="兑换可得余额/金豆" width="180" align="center">
        <template slot-scope="scope">
          {{ scope.row.exchange }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="180" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.created_at }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" width="180" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.updated_by_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后一次编辑时间" width="180" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.updated_at }}</span>
        </template>
      </el-table-column>
      <el-table-column label="编辑者" width="180" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.updated_by_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button icon="el-icon-edit" type="primary" size="mini" @click="handleUpdate(row)" />
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="currentPage" :limit.sync="pageSize" @pagination="fetchData({})" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="角色" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="icon" prop="icon">
          <el-upload
            action="/common/common/common/upload"
            list-type="picture-card"
            accept=".jpg,.jpeg,.png,.gif"
            :multiple="false"
            :data="productIconObj"
            :on-preview="handleProductIconCardPreview"
            :file-list="productIconArr"
            :on-remove="handleProductIconRemove"
            :on-success="handleProductIconUploadResult"
            :on-error="handleUploadError"
          >
            <i class="el-icon-plus" />
          </el-upload>
          <el-input v-model="temp.icon" type="hidden" />
          <el-dialog :visible.sync="dialogProductIconVisible" size="tiny">
            <img width="100%" :src="temp.icon" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="temp.type" class="filter-item" placeholder="请选择类型">
            <el-option v-for="(item, idx) in typeOptions" :key="item" :label="item" :value="idx" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="temp.type === 0" label="金豆" prop="price">
          <el-input-number v-model="temp.price" />
        </el-form-item>
        <el-form-item v-if="temp.type === 1" label="余额" prop="price">
          <el-input-number v-model="temp.price" />
        </el-form-item>
        <el-form-item v-if="temp.type === 0" label="余额" prop="exchange">
          <el-input-number v-model="temp.exchange" />
        </el-form-item>
        <el-form-item v-if="temp.type === 1" label="金豆" prop="exchange">
          <el-input-number v-model="temp.exchange" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="temp.stats" class="filter-item" placeholder="请选择状态">
            <el-option v-for="(item, idx) in StatsOptions" :key="item" :label="item" :value="idx" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create' ? createData() : updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getList, createIntegralProduct, editIntegralProduct, deleteImage } from '@/api/exchange'
import Pagination from '@/components/Pagination'

export default {
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: '启用',
        0: '禁用'
      }
      return statusMap[status]
    },
    statusCssFilter(status) {
      const statusMap = {
        1: 'success',
        0: 'info'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      const typeMap = {
        1: '余额转金豆',
        0: '金豆转余额'
      }
      return typeMap[type]
    },
    typeCssFilter(type) {
      const typeMap = {
        1: 'success',
        0: 'info'
      }
      return typeMap[type]
    }
  },
  data() {
    return {
      hidden: false,
      listLoading: true,
      // 翻页相关数据 当前页，每页显示条数，排序方式，排序字段，符合条件的搜索结果数，搜索结果
      currentPage: 1,
      pageSize: 10,
      sort: 'asc',
      order: 'id',
      total: 0,
      list: [],
      queryName: '',
      queryType: '',
      queryStats: '',
      sortBy: '',
      // 搜索条件相关数据
      StatsOptions: ['禁用', '启用'],
      typeOptions: ['金豆转余额', '余额转金豆'],
      showReviewer: false,
      // 弹出层数据
      // 是否隐藏弹出层
      dialogFormVisible: false,
      // 弹出层状态(创建、编辑)
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      // 临时数据
      temp: {
        id: undefined,
        name: '',
        type: 0,
        stats: 0,
        price: 0,
        exchange: 0,
        icon: ''
      },
      rules: {},
      // 下载的loading
      downloadLoading: false,
      downloadData: [],
      // icon
      productIconObj: {
        type: 'exchange_icon'
      },
      productIconArr: [],
      dialogProductIconUrl: '',
      dialogProductIconVisible: false
    }
  },
  mounted() {},
  created() {
    this.fetchData()
  },
  methods: {
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '',
        type: 0,
        stats: 0,
        price: 0,
        exchange: 0,
        icon: ''
      }
    },
    handleFilter() {
      this.currentPage = 1
      this.fetchData()
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)

      this.productIconArr = [{
        name: this.temp.icon,
        url: this.temp.icon,
        type: 'exchange_icon'
      }]

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const param = {
            id: this.temp.id,
            name: this.temp.name,
            type: this.temp.type,
            stats: this.temp.stats,
            price: this.temp.price,
            exchange: this.temp.exchange,
            icon: this.temp.icon
          }
          console.log(param)

          editIntegralProduct(param).then(response => {
            console.log(response)
            this.$notify({
              title: '编辑成功',
              type: 'success',
              message: '编辑成功',
              duration: 2000
            })
            this.fetchData()
            this.dialogFormVisible = false
          }).catch(error => {
            console.log('role update error: ' + error)
            this.$notify({
              title: '编辑失败',
              type: 'error',
              message: '编辑失败',
              duration: 2000
            })
          })
        }
      })
    },
    handleCreate() {
      this.resetTemp()
      this.productIconObj = {
        type: 'exchange_icon'
      }
      this.dialogStatus = 'create'
      this.dialogFormVisible = true

      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const param = {
            name: this.temp.name,
            type: this.temp.type,
            stats: this.temp.stats,
            price: this.temp.price,
            exchange: this.temp.exchange,
            icon: this.temp.icon
          }
          createIntegralProduct(param).then(response => {
            console.log(response)
            this.dialogFormVisible = false
            this.$notify({
              title: '创建成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
            this.fetchData()
            this.dialogFormVisible = false
          }).catch(() => {
            this.$notify({
              title: '创建失败',
              type: 'error',
              message: '创建失败',
              duration: 2000
            })
          })
        }
      })
    },
    handleDownload() {
      this.downloadLoading = true
      this.downloadLoading = false
    },
    formatJson(filterVal) {},
    fetchData() {
      this.listLoading = true
      const param = {
        sort: this.sort,
        order: this.order,
        page: this.currentPage,
        page_size: this.pageSize
      }
      if (this.queryName !== '') {
        param.name = this.queryName
      }
      if (this.queryType !== '') {
        this.typeOptions.map((item, idx) => {
          console.log(item)
          console.log(this.queryType)
          if (this.queryType === item) {
            // param.type = idx
          }
        })
      }
      if (this.queryStats !== '') {
        this.StatsOptions.map((item, idx) => {
          if (this.queryStats === item) {
            param.stats = idx
          }
        })
      }

      getList(param).then(response => {
        const { data, meta } = response
        this.list = data
        this.listLoading = false
        this.currentPage = parseInt(meta.current_page)
        this.total = parseInt(meta.total)
      }).catch(() => {
        this.listLoading = false
        this.list = []
      })
    },
    // 图片上传失败
    handleUploadError(err, file, fileList) {
      const resp = JSON.parse(err.message)
      this.$notify({
        title: '图片上传失败',
        type: 'error',
        message: resp.errmsg,
        duration: 2000
      })
    },
    handleProductIconUploadResult(response, file, fileList) {
      this.temp.icon = response.result.data.file
      // this.productIconArr = [{
      //   name: response.result.data.file,
      //   url: response.result.data.file,
      //   type: 'exchange_icon'
      // }]
      this.productIconObj = {
        name: response.result.data.file,
        url: response.result.data.file,
        type: 'exchange_icon'
      }
    },
    handleCategoryIconBeforeRemove(file, fileList) {
      // this.postForm.img_url = ''
      // console.log('handleCategoryIconBeforeRemove')
      // console.log(file)
      // console.log(fileList)
    },
    handleProductIconRemove(file, fileList) {
      console.log('handleProductIconRemove')

      const param = {
        url: this.productIconObj['url'],
        type: 'exchange_icon',
        exchange_id: this.temp.id
      }
      deleteImage(param).then(() => {
        console.log(file.url)
        console.log(this.temp.icon)
        // console.log(this.temp.icon.indexOf(file.url) !== -1)
        // if (this.temp.icon.indexOf(file.url) !== -1) {
        //   console.log(this.productImagesArr)
        //   console.log(this.temp.icon)
        //
        //   this.temp.icon = ''
        //   this.productIconArr = []
        //
        //   console.log(this.productIconArr)
        //   console.log(this.temp.icon)
        // }
        // this.$notify({
        //   title: '图片删除成功',
        //   type: 'success',
        //   message: '图片删除成功',
        //   duration: 2000
        // })
      }).catch(error => {
        this.$notify({
          title: '图片删除失败',
          type: 'error',
          message: error.errmsg,
          duration: 2000
        })
      })
    },
    handleProductIconCardPreview(file) {
      console.log('adsf')
      console.log(file.url)
      this.dialogMainImageUrl = file.url
      this.dialogMainImageVisible = true
      this.productIconObj = {
        name: file.url,
        url: file.url,
        type: 'exchange_icon'
      }
      console.log(this.productIconObj)
    }
  }
}
</script>
<style scoped>
  .filter-container {
    background: #fff;
    padding: 32px 16px;
  }
</style>
